package com.budwk.app.sqfwV2.component;

import com.budwk.app.sqfw.component.FromSummaryComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.TemplateIdsConstants;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.PdfGenerateParam;
import com.budwk.app.sqfwV2.dto.dto.WasteCategoryNewPdfDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownFileTypesResVo;
import com.budwk.app.sqfwV2.dto.vo.DocumentDownVo;
import com.budwk.app.sqfwV2.dto.vo.SummaryQueryReqVo;
import com.budwk.app.sqfwV2.enums.WasteCategoryFileServiceEnum;
import com.budwk.app.sqfwV2.generator.wasteCategory.pdf.RefuseClassifyDocGenerator;
import com.budwk.app.sqfwV2.generator.wasteCategory.pdf.RefuseClassifyYuHongDocGenerator;
import com.budwk.app.sqfwV2.service.SummarySafetyService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;

import java.util.*;
import java.util.stream.Collectors;

public class WasteCategoryComponent {

    /**
     * 判断当前操作人是否为云潭街道
     * @return
     */
    public static boolean isYunTanUser() {
        String userId = SecurityUtil.getUserId();
        SysUserService userService = NutzIocUtils.getBean(SysUserService.class);
        Sys_user user = userService.fetch(userId);
        return CommonConstants.YUNTAN_STREET.equals(user.getCommunity());
    }

    /**
     * 初始化数据
     * @param formSummarys
     * @param serviceEnum
     * @param type
     * @return
     */
    private static DownFileTypesResVo initData(List<Sqfw_formSummary_new> formSummarys, WasteCategoryFileServiceEnum serviceEnum, String type) {
        // 下载模板
        DownExcelLedgerReqVo reqVo = new DownExcelLedgerReqVo();
        reqVo.setDownTemplate(true)
                .setFileCode(serviceEnum.getCode())
                .setFileType(SupportBusinessTypeEnum.REFUSE_CLASSIFY.getName())
                .setDownFileType(type);
        DownFileTypesResVo resVo1 = WasteCategoryComponent.downTemplate(reqVo);

        // 下载数据
        DownFileTypesResVo resVo = new DownFileTypesResVo();
        resVo.setLabel(serviceEnum.getLabel())
                .setPreviewImage(List.of(serviceEnum.getPreviewImage().split(",")))
                .setFileCode(serviceEnum.getCode())
                .setFileTemplatePath(resVo1 != null ? resVo1.getFilePath() : null)
                .setHiveData(formSummarys.size() > 0)
                .setCreatedAt(System.currentTimeMillis());
        if ("pdf".equals(type)) {
            resVo.setFileType("pdf").setFileName(serviceEnum.getFileName()+".pdf")
                    .setIds(formSummarys.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList()));
        }
        if ("excel".equals(type)) {
            resVo.setFileType("excel")
                    .setFileName(serviceEnum.getFileName()+".xlsx")
                    .setIds(formSummarys.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
        }
        return resVo;
    }

    /**
     * 生成材料代码
     * @param formSummarys
     * @return
     */
    public static List<DownFileTypesResVo> generateFile(List<Sqfw_formSummary_new> formSummarys) {
        List<DownFileTypesResVo> list = new ArrayList<>();
        WasteCategoryFileServiceEnum excelEnum = WasteCategoryFileServiceEnum.ONE_EXCEL;
        WasteCategoryFileServiceEnum pdfEnum = WasteCategoryFileServiceEnum.ONE_PDF;
        if (isYunTanUser()) {
            excelEnum = WasteCategoryFileServiceEnum.TWO_EXCEL;
            pdfEnum = WasteCategoryFileServiceEnum.TWO_PDF;
        }
        DownFileTypesResVo resVo = initData(formSummarys, excelEnum, "excel");
        resVo.setLocation(1);
        list.add(resVo);
        DownFileTypesResVo resVo1 = initData(formSummarys, pdfEnum, "pdf");
        resVo.setLocation(2);
        list.add(resVo1);
        return list;
    }
    public static List<Sqfw_formSummary_new> listByConditionKey(String address, String fillType) {
        if (StringUtils.isEmpty(address)) {
            return Lists.newArrayList();
        }
        SqfwFormsummaryNewService formsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
        // 查询当前单位填报的数据
        Criteria cnd = Cnd.cri();
        SqlExpressionGroup criSql = cnd.where();
        criSql.andEquals(Sqfw_formSummary_new::getType, fillType)
                .andEquals(Sqfw_formSummary_new::getUnitId, SecurityUtil.getUnitId());
        criSql.and("param_data ->> 'address'", "like", "%" + address + "%");
        cnd.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        List<Sqfw_formSummary_new> list = formsummaryNewService.query(cnd);
        if (list.size() == 0) {
            return list;
        }
        // 按照最新的时间和场所名称去重
        Set<String> ps = new HashSet<>(); // 存储详细地址  唯一去重处理
        // 存储最终数据
        List<Sqfw_formSummary_new> result = new ArrayList<>();
        for (Sqfw_formSummary_new summaryNew : list) {
            if (StringUtils.isNotEmpty(summaryNew.getDetailAddress())) {
                Optional<String> first = ps.stream().filter(e -> summaryNew.getDetailAddress().equals(e)).findFirst();
                if (first.isEmpty()) {
                    ps.add(summaryNew.getDetailAddress());
                    result.add(summaryNew);
                }
            }
        }
        return result;
    }

    public static DownFileTypesResVo generateDetailFile(List<Sqfw_formSummary_new> formSummarys, SummaryQueryReqVo reqVo) {
        String fileCode = reqVo.getFileCode();
        Optional<WasteCategoryFileServiceEnum> first = WasteCategoryFileServiceEnum.listExcels().stream().filter(e -> e.getCode().equals(fileCode)).findFirst();
        if (first.isPresent()) {
            DownFileTypesResVo resVo = initData(formSummarys, first.get(), "excel");
            resVo.setLocation(1);
            return resVo;
        }

        Optional<WasteCategoryFileServiceEnum> pdfs = WasteCategoryFileServiceEnum.listPdfs().stream().filter(e -> e.getCode().equals(fileCode)).findFirst();
        if (pdfs.isPresent()) {
            DownFileTypesResVo resVo = initData(formSummarys, pdfs.get(), "pdf");
            resVo.setLocation(1);
            return resVo;
        }
        return new DownFileTypesResVo();
    }

    public static DownFileTypesResVo downTemplate(DownExcelLedgerReqVo reqVo) {
        String fileCode = reqVo.getFileCode();
        Optional<WasteCategoryFileServiceEnum> first = WasteCategoryFileServiceEnum.listExcels().stream().filter(e -> e.getCode().equals(fileCode)).findFirst();
        if (first.isPresent()) {
            // 属于excel模板
            SummarySafetyService summaryNewService = NutzIocUtils.getBean(SummarySafetyService.class);
            reqVo.setIds(new ArrayList<>()).setExcelCodes(List.of(fileCode)).setFileType(reqVo.getFileType());
            Result<List<GenerateExcelUrlVO>> result = summaryNewService.downloadFile(reqVo);
            // 初始数据返回
            GenerateExcelUrlVO generateExcelUrlVO = result.getData().get(0);
            DownFileTypesResVo fileTypesResVo = new DownFileTypesResVo();
            fileTypesResVo.setFileType(reqVo.getFileType()).setFileCode(fileCode).setFileTemplatePath(generateExcelUrlVO.getExcelUrl()).setFilePath(generateExcelUrlVO.getUrl());
            return fileTypesResVo;
        }
        Optional<WasteCategoryFileServiceEnum> pdfs = WasteCategoryFileServiceEnum.listPdfs().stream().filter(e -> e.getCode().equals(fileCode)).findFirst();
        if (pdfs.isPresent()) {
            // 属于pdf模板
            PdfGenerateParam pdfGenerateParam = FromSummaryComponent.initPdfGenerateParam();
            pdfGenerateParam.setAbstractCustomerPdfCreateField(new WasteCategoryNewPdfDTO());
            WasteCategoryFileServiceEnum serviceEnum = pdfs.get();
            if (serviceEnum.getCode().equals(WasteCategoryFileServiceEnum.ONE_PDF.getCode())) {
                reqVo.setIds(List.of(TemplateIdsConstants.WASTE_OTHER_IDS));
                DocumentDownVo documentDownVo = new DocumentDownVo();
                documentDownVo.setReqVo(reqVo).setBasePdfGenerator(new RefuseClassifyDocGenerator()).setPdfGenerateParam(pdfGenerateParam)
                        .setFileName(WasteCategoryFileServiceEnum.ONE_PDF.getFileName());
                return DocumentDownComponent.downWordDocTemplate(documentDownVo);
            }
            if (serviceEnum.getCode().equals(WasteCategoryFileServiceEnum.TWO_PDF.getCode())) {
                reqVo.setIds(List.of(TemplateIdsConstants.WASTE_YUHONG_IDS));

                DocumentDownVo documentDownVo = new DocumentDownVo();
                documentDownVo.setReqVo(reqVo).setBasePdfGenerator(new RefuseClassifyYuHongDocGenerator()).setPdfGenerateParam(pdfGenerateParam)
                        .setFileName(WasteCategoryFileServiceEnum.TWO_PDF.getFileName());
                return DocumentDownComponent.downWordDocTemplate(documentDownVo);
            }
        }
        return null;
    }
}
